package me.stone.stanimeclient.page.catalog

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.activityViewModels
import androidx.paging.LoadState
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.stone.stanimeclient.MainViewModel
import me.stone.stanimeclient.SACApplication
import me.stone.stanimeclient.base.AbsViewBindingFragment
import me.stone.stanimeclient.core.common.extensions.launchAndRepeatWithLifecycle
import me.stone.stanimeclient.core.ui.adapters.FanIntroListGridAdapter
import me.stone.stanimeclient.core.ui.adapters.MultiTypeFiltersAdapter
import me.stone.stanimeclient.core.ui.adapters.listener.OnItemClickListener
import me.stone.stanimeclient.core.ui.adapters.listener.OnItemSelectListener
import me.stone.stanimeclient.databinding.FragmentCatalogBinding
import timber.log.Timber
import javax.inject.Inject

@AndroidEntryPoint
class CatalogFragment: AbsViewBindingFragment<FragmentCatalogBinding>() {

    @Inject
    lateinit var filterAdapter: MultiTypeFiltersAdapter

    @Inject
    lateinit var pagingAdapter: FanIntroListGridAdapter

    private val mainViewModel: MainViewModel by activityViewModels()

    private val viewModel: CatalogViewModel by activityViewModels()

    private val sacApplication: SACApplication?
        get() = requireActivity().application as? SACApplication

    override fun buildViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ) : FragmentCatalogBinding {
        return FragmentCatalogBinding.inflate(
            inflater, container, false
        )
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        filterAdapter.selectListener = OnItemSelectListener {
            viewModel.putParams(it)
        }

        pagingAdapter.onItemClickListener = OnItemClickListener {
            mainViewModel.seeFanDetailItem(it.id)
        }

        binding.refresh.setOnRefreshListener {
            pagingAdapter.refresh()
        }

        binding.toggleType.setImageResource(pagingAdapter.currentViewType.next().drawableId)
        binding.toggleType.setOnClickListener {
            val drawable = pagingAdapter.toggleStyle().next().drawableId
            binding.toggleType.setImageResource(drawable)
        }

        binding.filter.adapter = filterAdapter
        binding.fans.adapter = pagingAdapter
        binding.progress.visibility = View.GONE
        binding.fans.visibility = View.VISIBLE

        launchAndRepeatWithLifecycle {
            launch {
                viewModel.filterData.collectLatest {
                    filterAdapter.submitList(it) {
                        filterAdapter.updateSelectedItems(viewModel.paramsStateData)
                    }
                }
            }

            launch {
                viewModel.paramDisplay.collectLatest {
                    binding.condition.text = it
                }
            }

            launch {
                viewModel.totalCount.collectLatest {
                    binding.total.text = it
                }
            }

            launch {
                viewModel.post.collect {
                    pagingAdapter.submitData(it)
                }
            }

            launch {
                pagingAdapter.loadStateFlow
                    .collect {
                        if (it.refresh is LoadState.Loading) {
                            showHideProgress(true)
                        } else if (mRefreshing && it.refresh is LoadState.NotLoading) {
                            showHideProgress(false)
                        }

                        if (it.hasError || it.refresh !is LoadState.Loading) {
                            binding.refresh.isRefreshing = false
                        }
                    }
            }

//            launch {
//                sacApplication?.darkThemeMode?.run {
//                    darkThemeModeFlow.collectLatest {
//                        Timber.d("clear recycled view pool")
//                        binding.filter.recycledViewPool.clear()
//                    }
//                }
//            }
        }
    }

    private var mRefreshing: Boolean = true

    private fun showHideProgress(refreshing: Boolean) {
        if (mRefreshing == refreshing) { return }
        mRefreshing = refreshing
        binding.progress.visibility = if (refreshing) View.VISIBLE else View.GONE
        binding.fans.visibility = if (refreshing) View.GONE else View.VISIBLE
    }

}